<?php

class UzytkownicyController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity())
        {
            $this->view->identity = $auth->getIdentity();
        }
    }
    
    public function loginAction()
    {
        $form = new Application_Form_Login();
        $form->setAction('/uzytkownicy/login')
                ->setMethod('post');
        if ($this->_request->isPost() && $form->isValid($_POST))
        {
            // pobieramy dane z formularza
            $data = $form->getValues();
            // pobieramy domyślny adapter bazy danych
            $db = Zend_Db_Table::getDefaultAdapter();
            // tworzymy instancję adaptera autoryzacji
            $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'uzytkownicy', 'username', 'haslo');
            // wprowadzamy dane do adaptera
            $authAdapter->setIdentity($data['username']);
            $authAdapter->setCredential(hash('sha512', $data['haslo']));
            // autoryzacja
            $result = $authAdapter->authenticate();
            if ($result->isValid())
            {
                // umieszczamy w sesji dane użytkownika
                $auth = Zend_Auth::getInstance();
                $storage = $auth->getStorage();
                $storage->write($authAdapter->getResultRowObject(array(
                            'username', 'adres', 'imie', 'nazwisko', 'rola'
                        )));
                return $this->_redirect('/uzytkownicy');
            }
            else
            {
                $this->view->loginMessage = "Niepoprawny login lub hasło";
            }
        }
        $this->view->form = $form;
    }

    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        return $this->_redirect('/');
    }


}

